/**
 * @Title: UserModal.js
 * @Description: UserModal
 * @author: Fanchao
 * @date: 2020/8/2 11:30 上午
 * @version V1.0
 */
import React, { memo, useState, useEffect } from 'react';
import { connect } from 'umi';
import { Form, DatePicker, Modal, Select, Input, Radio, TreeSelect, message, Cascader } from 'antd';
import moment from 'moment';
import { getRunTrainTaskInfoList, getTeachClassList, getTrainingTypeList } from 'api/index';
import { getChildCascader, getChildTreeData } from 'utils/index';

const { RangePicker } = DatePicker;
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
};
const { Option } = Select;
const UserModal = memo(({ cbClear, selectedRowKeys, selectedRows, schoolYearListOption, task: { itemData, examOptionList, expertTeacherListOption, treeData, questionCategoryList }, dispatch, title, visible }) => {
    const [defaultEvaluateTaskType, setDefaultEvaluateTaskType] = useState('student');
    const [trainingTypeList, setTrainingTypeList] = useState([]);
    const [runTrainTaskInfoList, setRunTrainTaskInfoList] = useState([]);
    const [teachClassList, setTeachClassList] = useState([]);

    const treeData1 = treeData.map(c => {
        if (!c.hasLowerDepartment) {
            return {
                title: c.departmentName,
                key: c.departmentId,
                comment: c.comment,
                hasLowerDepartment: c.hasLowerDepartment,
                level: c.level,
            };
        } else {
            return {
                title: c.departmentName,
                key: c.departmentId,
                comment: c.comment,
                hasLowerDepartment: c.hasLowerDepartment,
                level: c.level,
                children: getChildTreeData(c.lowerDepartmentModel),
            };
        }
    });
    const treeData2 = treeData.map(c => {
        if (!c.hasLowerDepartment) {
            return {
                value: c.departmentId,
                label: c.departmentName,
            };
        } else {
            return {
                value: c.departmentId,
                label: c.departmentName,
                children: getChildCascader(c.lowerDepartmentModel),
            };
        }
    });

    const fetchTrainingTypeList = async () => {
        const result = await getTrainingTypeList();
        if (result.status === 'success') {
            const trainingTypeList = result.result;
            setTrainingTypeList(trainingTypeList);
        } else {
            message.error(result.message);
        }
    };

    const fetchRunTrainTaskInfoList = async (filter) => {
        const result = await getRunTrainTaskInfoList({ trainingTypeId: filter });
        if (result.status === 'success') {
            const runTrainTaskInfoList = result.result;
            setRunTrainTaskInfoList(runTrainTaskInfoList);
        } else {
            message.error(result.message);
        }
    };
    const fetchTeachClassList = async () => {
        const result = await getTeachClassList();
        if (result.status === 'success') {
            const teachClassList = result.result;
            setTeachClassList(teachClassList);
        } else {
            message.error(result.message);
        }
    };
    useEffect(() => {
        fetchTrainingTypeList();
        fetchTeachClassList();
    }, []);
    const [form] = Form.useForm();
    form.setFieldsValue({
        evaluateTaskName: itemData.evaluateTaskName,
        comment: itemData.comment,
        time: itemData.evaluateTaskId ? [moment(itemData.evaluateTaskStartTime), moment(itemData.evaluateTaskEndTime)] : [],
    });
    const onChangeEvaluateTaskType = (defaultEvaluateTaskType) => {
        setDefaultEvaluateTaskType(defaultEvaluateTaskType);
    };
    const handleOnChangeX = (value) => {
        dispatch({
            type: 'task/getExamOptionList',
            payload: {
                questionCategoryName: value,
            },
        });
    };
    return (
        <Modal
            title={title}
            visible={visible}
            width="960px"
            onOk={() => {
                form.validateFields().then(values => {
                    if (itemData.evaluateTaskId) {
                        values.evaluateTaskId = itemData.evaluateTaskId;
                        values.taskStartDate = moment(values.time[0]).valueOf();
                        values.taskEndDate = moment(values.time[1]).valueOf();
                        delete values.time;
                        dispatch({
                            type: 'task/updateEvaluateTaskInfo',
                            payload: values,
                            callback: (result) => {
                                if (result) {
                                    form.resetFields();
                                    dispatch({
                                        type: 'task/setItemData',
                                        payload: {},
                                    });
                                    dispatch({
                                        type: 'task/setModalVisible',
                                        payload: false,
                                    });
                                    dispatch({
                                        type: 'task/getDataSource',
                                        payload: {
                                            keyword: '',
                                            reqPageInfo: {
                                                pageNumber: 1,
                                                pageSize: 10,
                                            },
                                        },
                                    });
                                }
                            },
                        });
                    } else {
                        values.taskStartDate = moment(values.time[0]).valueOf();
                        values.taskEndDate = moment(values.time[1]).valueOf();
                        values.evaluateObjectId = selectedRowKeys[0];


                        if (defaultEvaluateTaskType === 'student') {
                            values.leastDepartmentIds = values.unitIds;
                        } else if (defaultEvaluateTaskType === 'center') {
                            values.centerDepartment = values.unitIds.pop();
                        } else if (defaultEvaluateTaskType === 'teach_section') {
                            values.teachSectionDepartmentId = values.unitIds.pop();
                        }


                        delete values.time;
                        delete values.trainingTypeId;
                        delete values.majorDirectionId;
                        delete values.p1;
                        dispatch({
                            type: 'task/addEvaluateTask',
                            payload: values,
                            callback: (result) => {
                                if (result) {
                                    form.resetFields();
                                    dispatch({
                                        type: 'task/setItemData',
                                        payload: {},
                                    });
                                    dispatch({
                                        type: 'task/setModalVisible',
                                        payload: false,
                                    });
                                    dispatch({
                                        type: 'task/getDataSource',
                                        payload: {
                                            keyword: '',
                                            reqPageInfo: {
                                                pageNumber: 1,
                                                pageSize: 10,
                                            },
                                        },
                                    });
                                    cbClear && cbClear();
                                }
                            },
                        });
                    }
                }).catch(info => {
                });
            }}
            onCancel={() => {
                form.resetFields();
                dispatch({
                    type: 'task/setItemData',
                    payload: {},
                });
                dispatch({
                    type: 'task/setModalVisible',
                    payload: false,
                });
            }}
        >
            <Form
                {...layout}
                layout="horizontal"
                form={form}
                name="basic"
                // 表单默认值，只有初始化以及重置时生效 莫用
                initialValues={{
                    evaluateTaskType: defaultEvaluateTaskType,
                }}
            >
                <div>
                </div>
                <Form.Item
                    label="评定对象"
                >
                    <Input disabled value={
                        `${selectedRows[0]?.teacherRealName || itemData.teacherUserName}/${selectedRows[0]?.course || itemData.course}/${selectedRows[0]?.schoolYear || itemData.schoolYear}/${selectedRows[0]?.semester || itemData.semester}`
                    }/>
                </Form.Item>
                {
                    itemData.evaluateTaskId ? null : (
                        <>
                            <Form.Item
                                label="任务类型"
                                name="evaluateTaskType"
                                rules={[{ required: true, message: '必填' }]}
                            >
                                <Radio.Group
                                    onChange={(e) => onChangeEvaluateTaskType(e.target.value)}
                                >
                                    <Radio value="student">学生</Radio>
                                    <Radio value="school_expert">校专家</Radio>
                                    <Radio value="center_expert">部系中心专家</Radio>
                                    <Radio value="center">部系中心</Radio>
                                    <Radio value="teach_section">教研室</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                label="培训类型"
                                name="trainingTypeId"
                                rules={[{ required: true, message: '必填' }]}
                            >
                                <Select
                                    placeholder="培训类型"
                                    onChange={(e) => {
                                        fetchRunTrainTaskInfoList(e);
                                    }}
                                >
                                    {
                                        trainingTypeList.map(item => {
                                            return <Option key={item.trainTypeId}
                                                           value={item.trainTypeId}>{item.trainingTypeName}</Option>;
                                        })
                                    }
                                </Select>
                            </Form.Item>

                            <Form.Item
                                label="任务运行"
                                name="runTrainTaskId"
                                rules={[{ required: true, message: '必填' }]}
                            >
                                <Select
                                    placeholder="专业方向"
                                >
                                    {
                                        runTrainTaskInfoList.map(item => {
                                            return <Option key={item.runTrainTaskId}
                                                           value={item.runTrainTaskId}>{item.majorName}</Option>;
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </>
                    )
                }

                {
                    itemData.evaluateTaskId ? null : (
                        <>
                            <Form.Item
                                label="评教类型"
                                name="p1"
                                rules={[{ required: true, message: '必填' }]}
                            >
                                <Select
                                    placeholder="请选择评教类型"
                                    onChange={handleOnChangeX}
                                >
                                    {
                                        questionCategoryList.map(item => <Option value={item.questionCategoryName}
                                                                                 key={item.questionCategoryName}>{item.questionCategoryName}</Option>)
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="方案浏览"
                                name="evaluateExamId"
                                rules={[{ required: true, message: '必填' }]}
                            >
                                <Select
                                    placeholder="请选择方案浏览"
                                >
                                    {
                                        examOptionList.map(item => {
                                            return (
                                                <Option
                                                    key={item.evaluateExamId}
                                                    value={item.evaluateExamId}
                                                >
                                                    {`${item.examNo} ${item.examName}`}
                                                </Option>
                                            );
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </>
                    )
                }


                {
                    defaultEvaluateTaskType === 'school_expert' || defaultEvaluateTaskType === 'center_expert' && !itemData.evaluateTaskId ? (
                        <Form.Item
                            label="督导专家"
                            name="expertUserIdList"
                            rules={[{ required: true, message: '必填' }]}
                        >
                            <Select
                                mode="multiple"
                                placeholder="请选择督导专家"
                            >
                                {
                                    expertTeacherListOption.map(item => {
                                        return (
                                            <Option
                                                key={item.expertUserId}
                                                value={item.expertUserId}
                                            >
                                                {item.expertRealName}
                                            </Option>
                                        );
                                    })
                                }
                            </Select>
                        </Form.Item>
                    ) : null
                }
                <Form.Item
                    name="time"
                    label="开放时间"
                    rules={[{ type: 'array', required: true, message: '必填' }]}
                >
                    <RangePicker
                        style={{ width: '100%' }}
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                    />
                </Form.Item>
                <Form.Item
                    label="任务备注"
                    name="comment"
                >
                    <Input.TextArea placeholder="请输入任务备注"/>
                </Form.Item>
            </Form>
        </Modal>
    );
});

export default connect(({ task, dispatch }) => ({
    task,
    dispatch,
}))(UserModal);
